package edu.tjpu.share.newui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.FileForUpload;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.service.UploadService;
import edu.tjpu.share.task.ReadFileListTask;
import edu.tjpu.share.task.UserListTask;
import edu.tjpu.share.util.FileUtil;
import edu.tjpu.share.util.ListMapUtil;
import edu.tjpu.share.util.ListUtil;
import edu.tjpu.share.util.NetworkUtil;

public class UserList extends Activity {

	private UserVo user;
	private Server serverinfo;
	private int mid;
	private int gid;
	private int cid;
	private ListView listview;
	private Button selectAll, inverseSelect, cancleSelect, sendMsg;
	private int[] URelation;
	private List<Map<String, Object>> listmap;
	private List<Integer> checkuidList;
	private boolean isReg;
	private boolean withoutFile;
	private static boolean status;

	private static List<UserVo> userList;
	private static FileForUpload upfile;

	private SimpleAdapter messageAdapter;
	ProgressDialog progressDialog;
	// ProgressDialog uploadDialog;
	ProgressDialog readFileList;

	public static void setUserList(List<UserVo> userList) {
		UserList.userList = userList;
	}

	public static void setUpFile(FileForUpload upfile) {
		UserList.upfile = upfile;
	}

	public static void setStatus(boolean status) {
		UserList.status = status;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.getuser);
		listview = (ListView) findViewById(R.id.listView1);
		selectAll = (Button) findViewById(R.id.selectall);
		inverseSelect = (Button) findViewById(R.id.inverseselect);
		cancleSelect = (Button) findViewById(R.id.cancel);
		sendMsg = (Button) findViewById(R.id.sendmsg);

		checkuidList = new ArrayList<Integer>();

		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		// upfiles = (List<FileForUpload>)
		// bundle.getSerializable(Fields.FILE_LIST);
		gid = (Integer) bundle.getSerializable(Fields.GID);
		mid = (Integer) bundle.getSerializable(Fields.MID);
		cid = (Integer) bundle.getSerializable(Fields.CID);
		user = (UserVo) bundle.getSerializable(Fields.USER);
		isReg = (Boolean) bundle.getSerializable(Fields.IS_REG);
		serverinfo = (Server) bundle.getSerializable(Fields.SERVER_INFO);

		userList = null;
		status = false;
		withoutFile = false;

		progressDialog = ProgressDialog.show(UserList.this, "请稍等...",
				"正在连接服务器...", true);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put(Fields.SERVER_INFO, serverinfo);
		map.put(Fields.UID, user.getUid());
		map.put(Fields.CID, cid);
		map.put(Fields.GID, gid);
		map.put(Fields.MID, mid);
		map.put(Fields.HANDLER, handler);

		new UserListTask().execute(map);

		selectAll.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				for (int index = 0; index < listview.getChildCount(); index++) {
					LinearLayout layout = (LinearLayout) listview
							.getChildAt(index);
					CheckBox checkBox = (CheckBox) layout
							.findViewById(R.id.check);
					checkBox.setChecked(true);

					int uid = URelation[index];
					checkuidList.add(uid);
				}
			}
		});
		inverseSelect.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				for (int index = 0; index < listview.getChildCount(); index++) {
					LinearLayout layout = (LinearLayout) listview
							.getChildAt(index);
					CheckBox checkBox = (CheckBox) layout
							.findViewById(R.id.check);
					int uid = URelation[index];
					if (checkBox.isChecked()) {
						checkBox.setChecked(false);
						checkuidList.remove(Integer.valueOf(uid));
					} else {
						checkBox.setChecked(true);
						checkuidList.add(uid);
					}
				}
			}
		});
		cancleSelect.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				for (int index = 0; index < listview.getChildCount(); index++) {
					LinearLayout layout = (LinearLayout) listview
							.getChildAt(index);
					CheckBox checkBox = (CheckBox) layout
							.findViewById(R.id.check);
					int uid = URelation[index];
					checkBox.setChecked(false);
					checkuidList.remove(Integer.valueOf(uid));
				}
			}
		});
		sendMsg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				readFileList = ProgressDialog.show(UserList.this, "请稍等...",
						"正在读取缓存...", true);
				java.io.File cache = UserList.this.getCacheDir();

				HashMap<String, Object> mapread = new HashMap<String, Object>();
				mapread.put(Fields.FILE_URL, cache);
				mapread.put(Fields.HANDLER, handlerReadFileList);
				mapread.put(Fields.UID, checkuidList);
				new ReadFileListTask().execute(mapread);
			}
		});
	}

	private Handler handlerReadFileList = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (upfile != null) {

				readFileList.dismiss();
				if (upfile.getFname() == null || "".equals(upfile.getFname())) {
					upfile.setFname(upfile.getMsg() + ".msg");
					withoutFile = true;
				}

				Intent intent = getIntent();
				Bundle bundle = new Bundle();
				// UploadService

				if (NetworkUtil.CheckMobileNetworkState(UserList.this)&&!withoutFile) {
					new AlertDialog.Builder(UserList.this)
					.setTitle("警告")
					.setMessage("使用运营商网络上传可能产生高额流量费用，是否继续？")
					.setNegativeButton("等待连接至WLAN后自动上传",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									SharedPreferences sp = getSharedPreferences("perference", MODE_PRIVATE);
									if(sp.getBoolean(Fields.NEED_UPLOAD, false)){
										java.io.File cache = UserList.this.getCacheDir();
										java.io.File cacheForUpFile = new java.io.File(cache,Fields.FOR_UPLOAD);
										List<FileForUpload> upWaitingList = (List<FileForUpload>) FileUtil.ReadObjectFromFile(cacheForUpFile.getAbsolutePath());
										upWaitingList.add(upfile);
										FileUtil.writeObjectToFile(upWaitingList, cacheForUpFile.getAbsolutePath());
									}else{
									Editor editor = sp.edit();
									editor.putBoolean(Fields.NEED_UPLOAD, true);
									java.io.File cache = UserList.this.getCacheDir();
									java.io.File cacheForUpFile = new java.io.File(cache,Fields.FOR_UPLOAD);
									List<FileForUpload> upWaitingList = new ArrayList<FileForUpload>();
									upWaitingList.add(upfile);
									FileUtil.writeObjectToFile(upWaitingList, cacheForUpFile.getAbsolutePath());
									editor.commit();
									}
									Toast.makeText(UserList.this, "已添加至上传列表，连接至WLAN时自动开始上传！",Toast.LENGTH_SHORT).show();
								}
							})
					.setPositiveButton("现在上传",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Intent intent = getIntent();
									Bundle bundle = new Bundle();
									HashMap<String, Object> map = new HashMap<String, Object>();
									map.put(Fields.SERVER_INFO, serverinfo);
									map.put(Fields.FILE_FORUPLOAD, upfile);
									map.put(Fields.WITHOUTFILE, withoutFile);
									bundle.putSerializable("values", map);
									intent.putExtras(bundle);
									intent.setAction(UploadService.UPLOAD_ACTION);
									intent.setClass(UserList.this, UploadService.class);
									startService(intent);
								}
							}).show();
				} else {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put(Fields.SERVER_INFO, serverinfo);
					map.put(Fields.FILE_FORUPLOAD, upfile);
					map.put(Fields.WITHOUTFILE, withoutFile);
					bundle.putSerializable("values", map);
					intent.putExtras(bundle);
					intent.setAction(UploadService.UPLOAD_ACTION);
					intent.setClass(UserList.this, UploadService.class);
					startService(intent);
				}
				// UploadService

				intent = new Intent();
				bundle = new Bundle();

				bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
				bundle.putSerializable(Fields.USER, user);

				intent.putExtras(bundle);

				intent.setClass(UserList.this, MainTabHost.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
				startActivity(intent);
				finish();

			} else {
				readFileList.dismiss();
				Toast.makeText(UserList.this, "缓存读取失败！", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Fields.NETWORK_CONNECTION_ERROR) {
				progressDialog.dismiss();
				Toast.makeText(UserList.this, "网络错误！", Toast.LENGTH_SHORT)
						.show();
			} else {
				if (userList != null) {

					URelation = ListUtil.getUserIDRelation(userList);
					listmap = ListMapUtil.getUserListMap(userList);

					messageAdapter = new SimpleAdapter(UserList.this, listmap,
							R.layout.userlist, new String[] { "avatar",
									"uname", "check" }, new int[] {
									R.id.avatar, R.id.uname, R.id.check });
					messageAdapter
							.setViewBinder(new SimpleAdapter.ViewBinder() {

								@Override
								public boolean setViewValue(View view,
										Object data, String textRepresentation) {
									// 判断item中的Image组件
									if (view instanceof ImageView
											&& data instanceof Bitmap) {
										ImageView imageView = (ImageView) view;
										imageView.setImageBitmap((Bitmap) data);
										return true;
									}
									if (view instanceof CheckBox
											&& data instanceof Boolean) {
										CheckBox checkBox = (CheckBox) view;
										checkBox.setChecked((Boolean) data);
										return true;
									}
									return false;
								}
							});

					listview.setAdapter(messageAdapter);
					UserList.this.registerForContextMenu(listview);

					progressDialog.dismiss();

					listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							int uid = URelation[arg2];

							// arg0.findViewById(R.id.check);
							CheckBox cb = (CheckBox) arg1
									.findViewById(R.id.check);
							if (cb.isChecked()) {
								checkuidList.remove(Integer.valueOf(uid));
								cb.setChecked(false);
							} else {
								checkuidList.add(uid);
								cb.setChecked(true);
							}

						}
					});

				} else {
					progressDialog.dismiss();
					Toast.makeText(UserList.this, "服务器连接失败！",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	/*
	 * private Handler uploadhandler = new Handler() {
	 * 
	 * @Override public void handleMessage(Message msg) { if (status) {
	 * Toast.makeText(UserList.this, "向服务器上传成功！", Toast.LENGTH_SHORT) .show();
	 * 
	 * //uploadDialog.dismiss();
	 * 
	 * Intent intent = new Intent(); Bundle bundle = new Bundle();
	 * 
	 * bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
	 * bundle.putSerializable(Fields.USER, user);
	 * 
	 * intent.putExtras(bundle);
	 * 
	 * intent.setClass(UserList.this, MessageList.class);
	 * intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
	 * startActivity(intent); finish();
	 * 
	 * } else { //uploadDialog.dismiss(); Toast.makeText(UserList.this,
	 * "服务器连接失败！", Toast.LENGTH_SHORT) .show(); } } };
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.user_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		/*
		 * case R.id.userlist_next: // 保存继续 readFileList =
		 * ProgressDialog.show(UserList.this, "请稍等...", "正在读取缓存...", true);
		 * java.io.File cache = UserList.this.getCacheDir(); // java.io.File
		 * cache = new //
		 * java.io.File(Environment.getExternalStorageDirectory()+ // "/share");
		 * 
		 * HashMap<String, Object> mapread = new HashMap<String, Object>();
		 * mapread.put(Fields.FILE_URL, cache); mapread.put(Fields.HANDLER,
		 * handlerReadFileList); mapread.put(Fields.UID, checkuidList); new
		 * ReadFileListTask().execute(mapread);
		 * 
		 * return true;
		 */
		case R.id.userlist_cancle:
			// 取消
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putSerializable(Fields.CID, cid);
			bundle.putSerializable(Fields.MID, mid);
			bundle.putSerializable(Fields.GID, gid);
			bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
			// bundle.putSerializable(Fields.USER_LIST, (Serializable)userList);
			// bundle.putSerializable(Fields.FILE_LIST, (Serializable) upfiles);
			bundle.putSerializable(Fields.IS_REG, isReg);
			bundle.putSerializable(Fields.USER, user);

			intent.putExtras(bundle);

			intent.setClass(UserList.this, MessageList.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
			startActivity(intent);
			finish();
			return true;

		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	protected void onPause() {
		if (progressDialog != null)
			progressDialog.dismiss();
		// if (uploadDialog != null)
		// uploadDialog.dismiss();
		super.onPause();
	}

}
